/*
 * Copyright 2007-2008 Andrew O'Malley
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */


package ws.quokka.plugin.jetty;

import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.Path;

import org.mortbay.jetty.webapp.Configuration;
import org.mortbay.jetty.webapp.JettyWebXmlConfiguration;
import org.mortbay.jetty.webapp.TagLibConfiguration;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.jetty.webapp.WebInfConfiguration;
import org.mortbay.jetty.webapp.WebXmlConfiguration;

import ws.quokka.core.bootstrap_util.Logger;
import ws.quokka.core.bootstrap_util.Reflect;

import java.io.File;
import java.io.PrintWriter;
import java.io.StringWriter;

import java.net.MalformedURLException;
import java.net.URL;

import java.util.Arrays;
import java.util.List;


/**
 *
 */
public class PluginWebAppContext extends WebAppContext {
    //~ Instance fields ------------------------------------------------------------------------------------------------

    private Path classPathFiles;
    private File jettyEnvXmlFile;
    private File webXmlFile;
    private Logger log;

    //~ Methods --------------------------------------------------------------------------------------------------------

    public void setLog(Logger log) {
        this.log = log;
    }

    public void setWebXmlFile(File webXmlFile) {
        this.webXmlFile = webXmlFile;
    }

    public void setJettyEnvXmlFile(File jettyEnvXmlFile) {
        this.jettyEnvXmlFile = jettyEnvXmlFile;
    }

    public Path getClassPathFiles() {
        return classPathFiles;
    }

    public void setClassPathFiles(Path classPathFiles) {
        this.classPathFiles = classPathFiles;
    }

    public File getJettyEnvXmlFile() {
        return jettyEnvXmlFile;
    }

    public File getWebXmlFile() {
        return webXmlFile;
    }

    public void configure() {
        URL jettyEnvXmlUrl;

        try {
            jettyEnvXmlUrl = (jettyEnvXmlFile == null) ? null : jettyEnvXmlFile.toURI().toURL();
        } catch (MalformedURLException e) {
            throw new BuildException(e);
        }

        Configuration envConfig = null;

        // Attempt to create a JettyPlus configuration first. This will fail if the plus classes have
        // not been added to the class path. In that case, fall back to the standard configuration
        WebXmlConfiguration quokkaConfig;

        try {
            quokkaConfig = (WebXmlConfiguration)Class.forName("ws.quokka.plugin.jetty.PlusConfiguration").newInstance();
            envConfig = (Configuration)Class.forName("org.mortbay.jetty.plus.webapp.EnvConfiguration").newInstance();

            if (jettyEnvXmlUrl != null) {
                new Reflect().invoke(envConfig, "setJettyEnvXml", new Object[] { jettyEnvXmlUrl });
            }
        } catch (Throwable t) {
            quokkaConfig = new StandardConfiguration(jettyEnvXmlUrl);
        }

        List configurations = Arrays.asList(new Configuration[] {
                    new WebInfConfiguration(), quokkaConfig, new JettyWebXmlConfiguration(), new TagLibConfiguration()
                });

        if (envConfig != null) {
            configurations.add(envConfig);
        }

        setConfigurations((Configuration[])configurations.toArray(new Configuration[configurations.size()]));
    }

    protected void loadConfigurations() throws Exception {
        // Not sure how, but prior to restart the configurations get set to null.
        // The rest of the attributes seem to be left alone however, so this sets up the configurations again.
        configure();
        super.loadConfigurations();
    }

    public void doStart() throws Exception {
        setShutdown(false);
        super.doStart();
    }

    public void doStop() throws Exception {
        // This really doesn't belong here. Unfortunately, cobertura only saves coverage data on
        // JVM shutdown by default. This hack forces it to save the data.
        // TODO: find some way of generalising this behaviour so it is not cobertura specific
        try {
            String className = "net.sourceforge.cobertura.coveragedata.ProjectData";
            String methodName = "saveGlobalProjectData";
            Class saveClass = Class.forName(className, true, getClassLoader());
            java.lang.reflect.Method saveMethod = saveClass.getDeclaredMethod(methodName, new Class[0]);
            saveMethod.invoke(null, new Object[0]);
            log.verbose("Successfully saved cobertura data on Jetty stop");
        } catch (Throwable t) {
            if (log.isDebugEnabled()) {
                StringWriter writer = new StringWriter();
                t.printStackTrace(new PrintWriter(writer));
                log.debug("Unable to save cobertura data from PluginWebAppContext.doStop: " + writer.toString());
            }
        }

        setShutdown(true);

        // Wait a little while to ensure no requests are still being processed
        Thread.currentThread().sleep(500L);
        super.doStop();
    }
}
